function EventBus() { }
EventBus.prototype.eventMap = {};

//   监听事件的方法
EventBus.prototype.on = function (eventName, callback) {
  let events = this.eventMap[eventName];
  if (!events) {
    events = [];
    this.eventMap[eventName] = events;
  }
  events.push(callback);
}

//   触发事件的方法
EventBus.prototype.emit = function (eventName, ...args) {
  let events = this.eventMap[eventName];
  if (!events) return;
  events.forEach((Fn) => {
    Fn(...args);
  });
}

//   取消监听
EventBus.prototype.off = function (eventName, callback) {
  let events = this.eventMap[eventName];
  if (!events) return;
  let index = events.findIndex((Fn) => callback === Fn);
  events.splice(index, 1);

  // 如果 events 已经清空，从映射表中直接删除
  if (events.length === 0) delete this.eventMap[eventName];
}

//   清除监听
EventBus.prototype.clear = function (eventName) {
  // 如果没传事件名，清空所有回调
  if (!eventName) {
    this.eventMap = {};
    return;
  }
  // 如果传了事件名，清空该事件下所有回调
  let events = this.eventMap[eventName];
  if (!events) return;
  delete this.eventMap[eventName];
}

export default new EventBus();